# 截图宝 - 坐标点及选区选取对话框
# 作者： 魏新崇
# 邮箱： weixinchong [at] 163.com
# 项目主页：https://gitee.com/weixinchong/auto-igrab

import sys, pyautogui, time
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QPushButton, QSizePolicy
from PyQt5.QtGui import QPainter

class PointSelDialog(QWidget):

    def __init__(self, parent = None):
        super(PointSelDialog, self).__init__(parent)
        # 设定窗口状态
        self.setWindowState(Qt.WindowMaximized)
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setWindowOpacity(0.4)
        self.setCursor(Qt.CrossCursor)
        # 初始化位置坐标
        self.x_left = -100

    def mousePressEvent(self, event):
        '''鼠标按下时确定坐标'''
        x, y = pyautogui.position()
        self.o1.setValue(x)
        self.o2.setValue(y)
        if self.mode == 0:
            self.close()
        elif self.mode == 1:
            self.x_left = x
            self.y_top = y

    def mouseMoveEvent(self, event):
        '''鼠标拖动时绘制选区'''
        if self.mode == 1:
            self.x_right, self.y_bottom = pyautogui.position()
            self.update()  #触发绘图事件

    def paintEvent(self, QPaintEvent):
        '''重绘矩形区域'''
        if self.x_left > 0:
            painter = QPainter(self)
            painter.setBrush(Qt.black)
            painter.begin(self)
            painter.drawRect(self.x_left, self.y_top, self.x_right - self.x_left, self.y_bottom - self.y_top)
            painter.end()
    
    def mouseReleaseEvent(self, event):
        '''鼠标松开时确定完整选区'''
        if self.mode == 1:
            x, y = pyautogui.position()
            self.o3.setValue(x)
            self.o4.setValue(y)
            self.close()

    def setSinglePointObj(self, o1, o2):
        '''确定单个点的坐标'''
        self.mode = 0
        self.o1 = o1
        self.o2 = o2

    def get_pos(self):
        '''获得单个点的位置'''
        x, y = pyautogui.position()
        self.o1.setValue(x)
        self.o2.setValue(y)
        self.close()

    def setAreaObj(self, o1, o2, o3, o4):
        '''确定一个区域（左上角、右下角）的坐标'''
        self.mode = 1
        self.o1 = o1
        self.o2 = o2
        self.o3 = o3
        self.o4 = o4
